﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using T.FAS.Runtime.MF.Dao.Dao;
using T.FAS.Runtime.MF.Entity;

namespace T.FAS.Runtime.MF.Runtime.Core
{
    internal class MicroflowActivityFactory
    {
        private static readonly object s_lock = new object();
        private static readonly Dictionary<string, MicroflowActivity> s_cache = new Dictionary<string, MicroflowActivity>();
        static MicroflowActivityFactory() { }

        private MicroflowActivityFactory() { }
        public static MicroflowActivity GetMicroflowActivity(string activityID)
        {
            return Get(activityID);
        }
        public static MicroflowActivity Get(string activityID)
        {
            if (string.IsNullOrEmpty(activityID))
            {
                throw new ArgumentNullException(activityID);
            }
            try
            {
                if (s_cache.ContainsKey(activityID)) return s_cache[activityID];
                else
                {
                    lock (s_lock)
                    {
                        if (s_cache.ContainsKey(activityID)) return s_cache[activityID];
                        else
                        {
                            var list = GetMicroflowActivityList();
                            list.ForEach(item =>
                            {
                                s_cache[item.ID] = item;
                            });
                            if (s_cache.ContainsKey(activityID))
                                return s_cache[activityID];
                            else
                                return null;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private static List<MicroflowActivity> GetMicroflowActivityList()
        {
            try
            {
                var dao = new MicroflowActivityDao();
                return dao.GetTypedObjectsByFilter("1=1");
            }
            catch (Exception)
            {

                return new List<MicroflowActivity>();
            }

        }
    }
}
